package com.app.newcsc.fragment.main;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.app.newcsc.BR;
import com.app.newcsc.R;
import com.app.newcsc.app.AppApplication;
import com.app.newcsc.app.AppViewModelFactory;
import com.app.newcsc.databinding.FragmentTabFundBinding;
import com.app.newcsc.entity.Message;
import com.app.newcsc.entity.WalletEntity;
import com.app.newcsc.fragment.moneydetail.DetailFragment;
import com.app.newcsc.fragment.moneydetail.MoneyDetailFragment;
import com.app.newcsc.utils.NumberUtils;
import com.app.newcsc.utils.SpUtils;
import com.app.newcsc.utils.ToastUtils;
import com.app.newcsc.view.FundListAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;

/**
 * 资产
 *
 * @author: woking
 * @date: 2021/6/7
 * @description：
 */
public class FundFragment extends BaseFragment<FragmentTabFundBinding, FundViewModel> {
    private WalletEntity mAdWalletEntity = null;
    private WalletEntity mCSCWalletEntity = null;
    private WalletEntity mYongHuWalletEntity = null;
    private WalletEntity mFaBuWalletEntity = null;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_tab_fund;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public FundViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用NetWorkViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(FundViewModel.class);
    }

    private Disposable mSubscription;

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mSubscription != null) {
            RxSubscriptions.remove(mSubscription);
        }
    }

    @Override
    public void initData() {
        super.initData();

        showDialog("");
//        viewModel.walletCoins();//钱包类型
//        viewModel.otcWallet("");//钱包余额
        mSubscription = RxBus.getDefault().toObservable(Message.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(new Consumer<Message>() {
                    @Override
                    public void accept(final Message message) throws Exception {
                        Log.e("TAG", "===============message==============" + message.getName());
                        if (message.getName().equals("start_login") || message.getName().equals("RefreshExchange")) {
                            viewModel.walletCoins();//钱包类型
//                            viewModel.otcWallet("");//钱包余额
                        }
                    }
                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);
        viewModel.mWalletEntitys.observe(this, new Observer<List<WalletEntity>>() {
            @Override
            public void onChanged(List<WalletEntity> walletEntities) {
//                binding.listviewList.setAdapter(new FundListAdapter(getContext(), walletEntities));
                binding.listviewList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        SpUtils.put(getActivity(), "isLogin", "1");
                        Bundle bundle = new Bundle();
                        //                    bundle.putString("type","yonghu");
                        WalletEntity walletEntity = (WalletEntity) adapterView.getAdapter().getItem(i);
                        bundle.putString("type", ((AppApplication) AppApplication.getInstance()).getWalletCoinsId(walletEntity.coin_name));
                        bundle.putSerializable("data", walletEntity);
                        startContainerActivity(MoneyDetailFragment.class.getCanonicalName(), bundle);
                    }
                });

                boolean isTop = false;
                List<WalletEntity> walletEntitiesList = new ArrayList<>();
                for (int i = 0; i < walletEntities.size(); i++) {
                    WalletEntity mWalletEntity = walletEntities.get(i);
                    if (mWalletEntity.coin_name.equals("AD")) {
                        mAdWalletEntity = mWalletEntity;
                        binding.fountAdTv.setText(NumberUtils.keepPrecision(mWalletEntity.money, 4));
                        binding.typeTv.setText("可用" + mWalletEntity.coin_name);
                        double adNum = Double.valueOf(mWalletEntity.money) - Double.valueOf(mWalletEntity.lock_s_one);
                        setCanUseAd(String.valueOf(adNum));
                        binding.adNum.setText(NumberUtils.keepPrecision(String.valueOf(adNum), 4));
                        binding.dongjieTv.setText("冻结: " + NumberUtils.keepPrecision(mWalletEntity.freeze, 4) + mWalletEntity.coin_name);
                        binding.lockAdNum.setText(NumberUtils.keepPrecision(mWalletEntity.lock_s_one, 4));
                        binding.dayOpenTv.setText("每日释放:" + NumberUtils.keepPrecision(Double.valueOf(mWalletEntity.lock_one) * 0.005, 4) + mWalletEntity.coin_name);
                    } else if (mWalletEntity.coin_name.equalsIgnoreCase("CSC")) {
                        mCSCWalletEntity = mWalletEntity;
                        double cscNum = Double.valueOf(mWalletEntity.money) - Double.valueOf(mWalletEntity.lock_s_one);
                        setCanUseCsc(String.valueOf(cscNum));
                        binding.cscNum.setText(NumberUtils.keepPrecision(String.valueOf(cscNum), 4));
                        binding.lockCscNum.setText(NumberUtils.keepPrecision(mWalletEntity.lock_s_one, 4));
                        binding.dayCscOpenTv.setText("每日释放:" + NumberUtils.keepPrecision(Double.valueOf(mWalletEntity.lock_one) * 0.005, 4) + mWalletEntity.coin_name);
                        binding.cscDongjieTv.setText("冻结: " + NumberUtils.keepPrecision(mWalletEntity.freeze, 4) + mWalletEntity.coin_name);
                    } else if (mWalletEntity.coin_name.equals("用户账户") || mWalletEntity.coin_name.equals("发布账户") || mWalletEntity.coin_name.equals("积分")) {
                        continue;
                    }
                    walletEntitiesList.add(mWalletEntity);
//                    else if(mWalletEntity.coin_name.equals("CSC"))
//                    {
//                        mCSCWalletEntity= mWalletEntity;
//                        binding.fountCscTv.setText(NumberUtils.keepPrecision(mWalletEntity.money,4));
//                    }
//                    else if(mWalletEntity.coin_name.equals("用户账户"))
//                    {
//                        mYongHuWalletEntity = mWalletEntity;
//                        binding.fountYonghuTv.setText(NumberUtils.keepPrecision(mWalletEntity.money,4));
//                    }
//                    else if(mWalletEntity.coin_name.equals("发布账户"))
//                    {
//                        mFaBuWalletEntity = mWalletEntity;
//                        binding.fountFabuTv.setText(NumberUtils.keepPrecision(mWalletEntity.money,4));
//                    }
                }
                binding.listviewList.setAdapter(new FundListAdapter(getContext(), walletEntitiesList));
            }
        });
        initRefreshLayout();
    }

    private void initRefreshLayout() {
        binding.twinklingRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                viewModel.walletCoins();//钱包类型
//        viewModel.otcWallet("true");//钱包余额
            }
        });
        binding.twinklingRefreshLayout.setEnableLoadMore(false);
        binding.twinklingRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

            }
        });
//        binding.twinklingRefreshLayout.autoRefresh();
    }

    @Override
    public void onResume() {
        super.onResume();
        viewModel.walletCoins();//钱包类型
//        viewModel.otcWallet("true");//钱包余额
    }

    @Override
    public void initViewObservable() {
        //监听下拉刷新完成
        viewModel.uc.finishRefreshing.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
                binding.twinklingRefreshLayout.finishRefresh();
                dismissDialog();
            }
        });
        //监听上拉加载完成
        viewModel.uc.finishLoadmore.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
                binding.twinklingRefreshLayout.finishLoadMore();
//                viewModel.dismissDialog();
            }
        });

        binding.tvAdDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mAdWalletEntity.lock_time.equals("0")) {
                    Bundle bundle = new Bundle();
                    bundle.putString("coin_id", mAdWalletEntity.coin_id);
                    startContainerActivity(DetailFragment.class.getCanonicalName(), bundle);
                } else {
                    ToastUtils.toastLong("暂无明细");
                }
            }
        });

        binding.tvCscDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mCSCWalletEntity.lock_time.equals("0")) {
                    Bundle bundle = new Bundle();
                    bundle.putString("coin_id", mCSCWalletEntity.coin_id);
                    startContainerActivity(DetailFragment.class.getCanonicalName(), bundle);
                } else {
                    ToastUtils.toastLong("暂无明细");
                }
            }
        });
    }
}